package SEG_ApplicationLayer;

import CommonApplicationLayer.SMSComun;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import CommonBusinessLayer.TestComunBL;
import java.awt.Cursor;

public class FrmSEG_ConfigurarConexion extends JDialog {

    public FrmSEG_ConfigurarConexion(JFrame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        smsError = new errorProvider.FErrorProvider();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        btnCerrar = new boton.FButton();
        btnAceptar = new boton.FButton();
        btnProbar = new boton.FButton();
        jLabel2 = new javax.swing.JLabel();
        txtMotor = new javax.swing.JTextField();
        txtServidor = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtBaseDatos = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        txtPassword = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Configuración de la Conexión");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setFont(new java.awt.Font("Lucida Fax", 1, 10)); // NOI18N
        jLabel1.setText("Configurar Conexión a Base de Datos");

        btnCerrar.setText("Cerrar");
        btnCerrar.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        btnCerrar.setVisualStyle(3);
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        btnAceptar.setText("Aceptar");
        btnAceptar.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        btnAceptar.setVisualStyle(3);
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnProbar.setText("Probar Conexión");
        btnProbar.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        btnProbar.setVisualStyle(3);
        btnProbar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnProbarActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jLabel2.setText("Motor de BD:");

        txtMotor.setEditable(false);
        txtMotor.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        txtMotor.setText("Sql Server 2008 R2");

        txtServidor.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N

        jLabel3.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jLabel3.setText("Servidor:");

        jLabel4.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jLabel4.setText("Base de Datos:");

        txtBaseDatos.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N

        jLabel5.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jLabel5.setText("Usuario:");

        jLabel6.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jLabel6.setText("Contraseña:");

        txtUsuario.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N

        txtPassword.setFont(new java.awt.Font("Lucida Fax", 1, 10)); // NOI18N
        txtPassword.setEchoChar('*');

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(btnProbar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                                .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap())))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(txtMotor, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txtServidor, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel6))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtBaseDatos, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(txtPassword, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(txtUsuario, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtMotor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtBaseDatos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 186, Short.MAX_VALUE)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnProbar, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        SAXBuilder builder = new SAXBuilder();
        File xmlFile = new File("conexion.xml");
        
        try{
            if ( xmlFile.isFile() ){
                Document document = (Document) builder.build(xmlFile);
                Element rootNode = document.getRootElement();
                List list = rootNode.getChildren( "Conexion" );
                
                if ( list.size()>0 ){
                    Element conexion = (Element) list.get(0);
                    List parametros = conexion.getChildren();
                    
                    if (parametros.size()==4){
                        txtServidor.setText(((Element)parametros.get(0)).getTextTrim());
                        txtBaseDatos.setText(((Element)parametros.get(1)).getTextTrim());
                        txtUsuario.setText(((Element)parametros.get(2)).getTextTrim());
                        txtPassword.setText(((Element)parametros.get(3)).getTextTrim());
                    }
                    else{
                        JOptionPane.showMessageDialog(this, "El archivo de configuración esta dañado.", SMSComun.smsEmpresa, JOptionPane.WARNING_MESSAGE);
                    }
                }
                else{
                    JOptionPane.showMessageDialog(this, "El archivo de configuración esta dañado.", SMSComun.smsEmpresa, JOptionPane.WARNING_MESSAGE);
                }
            }
            else{
                JOptionPane.showMessageDialog(this, "No se encontro el archivo de configuración.", SMSComun.smsEmpresa, JOptionPane.WARNING_MESSAGE);
            }
        } catch(IOException ex){
            JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
        } catch (JDOMException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_formWindowOpened

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        if(esValido())
        {
            try {
                Element root = new Element("Root");
                Document doc = new Document(root);

                Element conexion = new Element("Conexion");
                conexion.addContent(new Element("Servidor").setText(txtServidor.getText()));
                conexion.addContent(new Element("BaseDatos").setText(txtBaseDatos.getText()));
                conexion.addContent(new Element("Usuario").setText(txtUsuario.getText()));
                conexion.addContent(new Element("Clave").setText(String.valueOf(txtPassword.getPassword())));
                doc.getRootElement().addContent(conexion);
                XMLOutputter xmlOutput = new XMLOutputter();
                xmlOutput.setFormat(Format.getPrettyFormat());
                xmlOutput.output(doc, new FileWriter("conexion.xml"));
                dispose();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        this.setVisible(false);
        dispose();
    }//GEN-LAST:event_btnCerrarActionPerformed

    private void btnProbarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProbarActionPerformed
        try {
            setCursor(new Cursor(Cursor.WAIT_CURSOR));
            if ( TestComunBL.getInstancia().ValidaConexion(txtServidor.getText(), txtBaseDatos.getText(), txtUsuario.getText(), String.valueOf(txtPassword.getPassword())) ) {
                JOptionPane.showMessageDialog(this, "Conexión realizada con exitó.", SMSComun.smsEmpresa, JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (Exception ex){
            JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
        } finally {
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    }//GEN-LAST:event_btnProbarActionPerformed

    private boolean esValido(){
        smsError.setVisible(false);
        
        if (txtServidor.getText().isEmpty()){
            smsError.setError(txtServidor, SMSComun.smsValorRequerido);
            return false;
        }
        if (txtBaseDatos.getText().isEmpty()){
            smsError.setError(txtBaseDatos, SMSComun.smsValorRequerido);
            return false;
        }
        if (txtUsuario.getText().isEmpty()){
            smsError.setError(txtUsuario, SMSComun.smsValorRequerido);
            return false;
        }
        if (String.valueOf(txtPassword.getPassword()).isEmpty()){
            smsError.setError(txtPassword, SMSComun.smsValorRequerido);
            return false;
        }
        
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private boton.FButton btnAceptar;
    private boton.FButton btnCerrar;
    private boton.FButton btnProbar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private errorProvider.FErrorProvider smsError;
    private javax.swing.JTextField txtBaseDatos;
    private javax.swing.JTextField txtMotor;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtServidor;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
